package com.ynu.znkz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ynu.znkz.entity.*;
import com.ynu.znkz.entity.vo.QueryPaperVo;
import com.ynu.znkz.entity.vo.SecondLevelResearchObj;
import com.ynu.znkz.entity.vo.TopLevelResearchObj;
import com.ynu.znkz.mapper.PaperMapper;
import com.ynu.znkz.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Service
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements PaperService {
    @Autowired
    private PaperService paperService;

    @Autowired
    private PaperPaperInfoService paperInfoService;

    @Autowired
    private PaperResearchMethodService researchMethodService;

    @Autowired
    private PaperResearchObjService researchObjService;

    @Autowired
    private PaperFocusService focusService;

    @Autowired
    private PaperResearchProblemService researchProblemService;

    @Autowired
    private UserService userService;

    /**
     * 条件查询分页
     * @param pageParam
     * @param queryPaperVo
     */
    @Override
    public void pageQuery(Page<Paper> pageParam, QueryPaperVo queryPaperVo) {
        //构建条件
        QueryWrapper<Paper> queryWrapper = new QueryWrapper<>();

        //判断条件是否为空，若不空则拼接条件
        String keyWord = queryPaperVo.getKeyWord();
        String researchObjId = queryPaperVo.getResearchObjId();
        String researchObjSonId = queryPaperVo.getResearchObjSonId();
        String researchMethodId = queryPaperVo.getResearchMethodId();
        String researchProblemId = queryPaperVo.getResearchProblemId();
        String focusId = queryPaperVo.getFocusId();
        String begin = queryPaperVo.getBegin();
        String end = queryPaperVo.getEnd();
        String createPerson = queryPaperVo.getCreatePerson();

        //模糊匹配
        if(!StringUtils.isEmpty(keyWord)) queryWrapper.like("paper_name", keyWord);
        //=
        if(!StringUtils.isEmpty(researchObjId)) queryWrapper.eq("research_obj_id", researchObjId);

        if(!StringUtils.isEmpty(researchObjSonId)) queryWrapper.eq("research_obj_son_id", researchObjSonId);

        if(!StringUtils.isEmpty(researchMethodId)) queryWrapper.eq("research_method_id", researchMethodId);

        if(!StringUtils.isEmpty(researchProblemId)) queryWrapper.eq("research_problem_id", researchProblemId);

        if(!StringUtils.isEmpty(focusId)) queryWrapper.eq("focus_id", focusId);
        //>=
        if (!StringUtils.isEmpty(begin)) queryWrapper.ge("create_date", begin);
        //<=
        if (!StringUtils.isEmpty(end)) queryWrapper.le("create_date", end);

        if(!StringUtils.isEmpty(createPerson)) queryWrapper.eq("create_person", createPerson);

        //为展示更友好，设置按照新增时间降序排序
        queryWrapper.orderByDesc("create_date");

        //调用方法实现条件分页
        baseMapper.selectPage(pageParam, queryWrapper);
    }

    /**
     * 获取研究方法分类集合
     * @return
     */
    @Override
    public List<PaperResearchMethod> getAllResearchMethod() {
        return researchMethodService.list(null);
    }

    /**
     * 封装研究对象分类集合（树形）
     * @return
     */
    @Override
    public List<TopLevelResearchObj> getAllResearchObj() {
        //最终返回的集合
        List<TopLevelResearchObj> finalList = new ArrayList<>();
        //查询所有一级分类信息
        List<PaperResearchObj> topLevelList = researchObjService.getAllTopLevel();
        //查询所有二级分类信息
        List<PaperResearchObj> secondLevelList = researchObjService.getSecondLevel();
        for (PaperResearchObj top : topLevelList) {
            TopLevelResearchObj topLevel = new TopLevelResearchObj();
            BeanUtils.copyProperties(top, topLevel);
            List<SecondLevelResearchObj> children = new ArrayList<>();
            for (PaperResearchObj second : secondLevelList) {
                if(second.getParentId().equals(top.getId())) {
                    SecondLevelResearchObj secondLevelResearchObj = new SecondLevelResearchObj();
                    BeanUtils.copyProperties(second, secondLevelResearchObj);
                    children.add(secondLevelResearchObj);
                }
            }
            topLevel.setSecondLevelResearchObjList(children);
            finalList.add(topLevel);
        }
        return finalList;
    }

    /**
     * 获取研究焦点分类集合
     * @return
     */
    @Override
    public List<PaperFocus> getAllFocus() {
        return focusService.list(null);
    }

    /**
     * 获取研究问题分类集合
     * @return
     */
    @Override
    public List<PaperResearchProblem> getAllResearchProblem() {
        return researchProblemService.list(null);
    }

    /**
     * 获取所有用户信息集合
     * @return
     */
    @Override
    public List<User> getAllUser() {
        return userService.list(null);
    }

    //搜索某个论文
    @Override
    public String seachPaper(String paperName) {
        QueryWrapper<PaperPaperInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_name",paperName);
        List<PaperPaperInfo> paperPaperInfos = paperInfoService.list(wrapper);
        //数据库中没有该论文，返回no
        if(paperPaperInfos.isEmpty()){
            return "no";
        }
        return "yes";
    }

    @Override
    public String addPaper(String userNme,Paper paper) {
        QueryWrapper<PaperPaperInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("paper_name",paper.getPaperName());
        List<PaperPaperInfo> paperPaperInfos = paperInfoService.list(wrapper);
        if(!paperPaperInfos.isEmpty()){
            return "论文已经在数据库中";
        }else {
            //把论文添加到数据库中
            String researchObjId = researchObjService.savePaperResearchObj(paper.getResearchObjName(),"0");
            String researchObjSonId = researchObjService.savePaperResearchObj(paper.getResearchObjSonName(),researchObjId);
            String researchProblemId = researchProblemService.savePaperResearchProblem(paper.getResearchProblemName());
            String researchMethodId = researchMethodService.savePaperResearchMethod(paper.getResearchMethodName());
            String researchFocusId = focusService.savePaperFocus(paper.getFocusName());


            paper.setPaperName(paper.getPaperName());
            paper.setCreatePerson(userNme);
            paper.setResearchObjSonId(researchObjSonId);
            paper.setResearchObjId(researchObjId);
            paper.setFocusId(researchFocusId);
            paper.setResearchProblemId(researchProblemId);
            paper.setResearchMethodId(researchMethodId);
            paperService.save(paper);

            return "论文上传成功";
        }
    }

    /**
     * 根据论文的名称删除论文
     * @param paperName
     * @return
     */
    @Override
    public boolean removePaper(String paperName) {
        ///E:/Java/dev/ideaworkspace/paper-database/target/classes/uploadFile
        String filePath = Thread.currentThread().getContextClassLoader().getResource("uploadFile").getPath();
        String fileName = filePath+"/"+paperName+".pdf";
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

}
